<template>
	<view class="p30">
		<!-- 运营商开通暂存功能 -->
		<view class="" v-if="isIF">
			<view class="BtopList">
				<view class="BtopList1">
					<view class="BtopListOne" v-for="(item,index) in Blist" :key="index"
						@click="listFn(index,item.text)">
						<text class="BtopListOne1" :class="Bnum===index?'blue':'' ">{{item.text}}</text>
					</view>
				</view>
				<view class="" v-if="!showModal">
					<view class="BtopListTwo">直接选取你的“寄存天数”，点击使用</view>
					<view class="BtopListTwo">扫设备二维码归还电池</view>
					<view class="BtopListTwo">提示寄存成功即可</view>
				</view>

			</view>
			<view style="position: absolute;left: 21%;top: 29%;z-index: 1000;" v-if="showModal">
				<modal title="自定义寄存天数" confirm-text="确定" cancel-text="取消" @cancel="cancelPop" @confirm="confirmPop">
					<input :placeholder="'请输入寄存天数,不得超过'+ dataList.holdDay+'天'" v-model="inputValue"
						style="padding: 20upx;border: 1upx solid #ddd;margin-top: 20upx;margin-bottom: 20upx;" />
				</modal>
			</view>


			<view class="mb60 plr24 ptb30 bgf5 border-r1 Bconent" v-if="true">
				<view class="h50" style="font-size: 30upx;color: black;font-weight: 700;">你的换电套餐：</view>
				<view class="h50">总换电次数：{{ scanList.nums ===-1 ? '无限' : scanList.nums ? scanList.nums:'--' }}次</view>
				<view class="h50">剩余换电次数：{{ scanList.num  ===-1 ? '无限' : scanList.num ?scanList.num:'--' }}次</view>
				<view class="h50">套餐结束时间：{{ scanList.validityTime ? scanList.validityTime :'--'  }}</view>
				<view class="h50">套餐电池类型：{{ scanList.btType ?scanList.btType :'--'}}V</view>
			</view>
			<!-- 规则 -->
			<view class="Bfooter">
				<view class="BfooterTitle">规则说明</view>
				<view class="Bfooterp">
					1.寄存劵1次最多使用一张；30天内{{dataList.holdDay===0?'不限天数寄存':'最多寄存'+dataList.holdDay+'天'}},或30天内{{dataList.total===0?'不限次寄存':'最多寄存'+dataList.total+'次'}};
				</view>
				<view class="">2.目前你已寄存{{dataListss.count}}次，{{dataListss.sum}}天;</view>
				<!-- <view class="Bfooterp">3.此劵当天有效；</view> -->
				<view class="Bfooterp">3.活动的最终解释权归公司所有；</view>
			</view>

			<view class="BfooterF">
				<u-button type="primary" shape="circle" @click="useFn" :disabled="isTapScan">使用</u-button>
			</view>
		</view>
		<!-- 运营商没开通暂存功能 -->
		<view class="" v-if="!isIF">
			该商户暂未开通此功能，敬请期待...
		</view>
	</view>

</template>
<script>
	import {
		HOST
	} from '@/config';
	import {
		mapState
	} from 'vuex'
	import {
		couponListByUser,
		couponGetUserCoupon,
		APIreceive,
		operatorGetGiveInfo,
		couponHoldCoupon,
		scanDevice,
		deviceReturnOpenDoor,
		holdGetHold,
		holdUseHold,
		depositOrder,
		holdUseHoldV2,
		getMyBattery
	} from '@/api/user.js'
	export default {
		data() {
			return {
				initList: [],
				idList: [],
				newList: [],
				isTwo: false,
				isOne: false,
				isNew: false,
				cashShow: false,
				isShow: false,
				cashContent: '',
				isContent: '',
				temporaryObj: {},
				query: {},
				info: {},
				mealState: '',
				zdeviceId: '',
				isTapScan: false, // 是否可以正常扫码 （阻止用户同一时间点，多次点击）
				Bnum: 0,
				showModal: false,
				inputValue: "",
				isIF: false,
				dataList: {},
				dataListss: {},
				scanList: {},
				handlerType: 1, //3是从寄存电池页回来的  1是没事发生
				isBtn: 1, //电池归还状态  1已归还  0未归还
				Blist: [{
						text: '寄存1天'
					},
					{
						text: '寄存2天'
					},
					{
						text: '寄存3天'
					},
					{
						text: '寄存4天'
					},
					{
						text: '寄存5天'
					},
					{
						text: '寄存6天'
					},
					{
						text: '寄存7天'
					},
					{
						text: '自定义'
					},
				],
			}
		},
		computed: {
			...mapState({
				agentIdss: state => state.user.agentIdss,
				latitudess: state => state.user.latitudess,
				longitudess: state => state.user.longitudess,
				token: state => state.user.token,
			})

		},
		async onLoad(e) {
			console.log('3333333', e);
			this.mealState = e.mealState
			this.zdeviceId = e.deviceId
			this.handlerType = e.handlerType || 1
			if (this.handlerType == 3) { //从寄存电池页回来
				// this.depositOrderFn()
				setTimeout(async () => {
					const getMyBatt = await getMyBattery()
					if (getMyBatt.code == 200 && getMyBatt.data.batteryNo) {
						console.log('有电池在手');
						this.isBtn = 0
					} else {
						this.isBtn = 1
					}
					if (this.isBtn == 1) { //电池归还状态  1已归还
						// const en = await holdUseHold({
						// 	day: e.numberDay,
						// })
						// if (en.code === 200) {
						this.toast('寄存成功')
						this.isTapScan = true
						// }
					} else {
						this.toast('寄存失败')
					}


					this.query = uni.getStorageSync('query') || {}
					setTimeout(() => {
						this.ScanssFn(e.deviceNo)
						this.LoadFn()
					}, 1500)
				}, 500)
			}
		},
		onShow() {
			this.LoadFn()
			this.info = uni.getStorageSync('oneData') || {}
			this.query = uni.getStorageSync('query') || {}
			if (this.handlerType === 1) {
				this.ScanssFn()
			}
			// this.depositOrderFn()
			console.log('vuex值', this.agentIdss, this.latitudess, this.longitudess, this.token);
		},
		methods: {
			// 查询用户手上有没有电池
			// async depositOrderFn() {
			// 	const res = await depositOrder({
			// 		pageNum: 1,
			// 		pageSize: 20
			// 	})
			// 	// 只有等于0才是还没归还电池，其他都是已归还
			// 	this.isBtn = res.rows[0].rent_status == 0 ? 0 : 1 //电池租用状态，0 未归还， 1 已归还(已完成) 2:退款中 3:已退款    
			// 	console.log('电池归还状态', res.rows, this.isBtn);
			// },

			// 使用
			async useFn() {
				const getMyBatt = await getMyBattery()
				if (getMyBatt.code == 200 && getMyBatt.data.batteryNo) {
					console.log('有电池在手');
					this.isBtn = 0
				} else {
					this.isBtn = 1
					this.toast('请先租电，还电池时再使用寄存')
					this.isTapScan = true
					uni.reLaunch({ //押金退电
						url: `/pages/main/mine`,
					});
				}

				// 天数
				let ss = Number(this.dataList.holdDay) == 0 ? 100000 : Number(this.dataList.holdDay) - Number(this
					.dataListss.sum)
				// 次数
				let aa = Number(this.dataList.total) == 0 ? 100000 : Number(this.dataList.total) - Number(this
					.dataListss.count)
				console.log('222', this.dataList.holdDay, ss, aa, this.dataList.total);
				if (aa === 0) {
					this.toast(`30天内最多寄存${this.dataList.total}次,你的寄存次数已用完`)
					return
				}
				// dataList.holdDay===0?'不限天数寄存':'最多寄存'+dataList.holdDay+'天'}},或30天内{{dataList.total===0?'不限次寄存':'最多寄存'+dataList.total+'次'
				if (this.Bnum === 7) {
					if (this.inputValue > ss) {
						this.toast(`30天内最多寄存${this.dataList.holdDay}天,目前你已寄存${this.dataListss.sum}天`)
						return
					}
				} else {
					if ((this.Bnum + 1) > ss) {
						this.toast(`30天内最多寄存${this.dataList.holdDay}天,目前你已寄存${this.dataListss.sum}天`)
						return
					}
				}

				// 已经归还了电池
				if (this.isBtn === 1) {
					this.toast(`你已经归还了电池，无需使用该寄存功能，即将返回上一页...`)
					setTimeout(() => {
						uni.navigateBack({
							delta: 1,
						})
					}, 2000)
					return false
					// let num = this.Bnum + 1
					// const en = await holdUseHold({
					// 	day: num === 8 ? this.inputValue : num,
					// })
					// if (en.code === 200) {
					// 	this.toast('寄存成功')

					// } else {
					// 	this.toast('寄存失败')
					// }
					// setTimeout(() => {
					// 	this.ScanssFn()
					// 	this.LoadFn()
					// }, 2000)
				} else { // 没归还电池的时候调用归还电池
					this.returnTheBatteryFn()
				}
				console.log('this.Bnum', this.Bnum);
			},
			// 获取运营商有没有开通暂存功能
			async LoadFn() {
				const res = await holdGetHold()
				// 如果运营商没开通暂存劵功能
				if (!res.data || Object.keys(res.data).length === 0) {
					this.isIF = false
				} else {
					this.isIF = true
					this.dataList = res.data.hold
					this.dataListss = res.data.userUse

				}
			},
			// 自定义--确认
			confirmPop() {
				this.useFn()
				// this.showModal = false
			},
			// 自定义--取消
			cancelPop() {
				this.showModal = false
			},
			listFn(val, text) {
				console.log('1111', val, text);
				this.Bnum = val
				if (text === '自定义') {
					this.showModal = true;
					this.inputValue = ''

				} else {
					this.showModal = false
				}
			},
			async ScanssFn(deviceNo) {
				let query = {
					deviceNo: deviceNo || this.query.deviceNo,
					lat: this.query.lat || '',
					lng: this.query.lng || '',
					token: this.query.token || '',
				}
				const scan = await scanDevice(this.query)
				this.scanList = scan.data || {}
				if (scan.code !== 200) {
					this.toast('请扫描正确的二维码！')
				}
			},
			async returnTheBatteryFn() {
				// let gb = this.Bnum === 7 ? this.inputValue : this.Bnum
				// console.log('归还成功', '固定优惠券：', this.Bnum, '自定义：', this.inputValue, '最终：', gb);
				// return false
				// 防抖
				if (this.isTapScan) {
					return false
				}
				this.isTapScan = true
				setTimeout(() => {
					this.isTapScan = false
				}, 2000)
				const _self = this
				// 调起扫码接口
				uni.scanCode({
					scanType: ['barCode', 'qrCode'], //扫码类型
					// 扫码成功
					async success(res) {
						if (res.errMsg == 'scanCode:ok') {
							// 当扫不是本域名时提示,即res.result.indexOf(HOST)为-1
							if (res.result.indexOf(HOST) === -1) {
								_self.toast('请扫描正确的二维码！')
								return
							}
							let deviceNo = ''
							let deviceType = 0
							if (res.scanType == 'QR') { //扫的码是二维码类型
								// deviceType设备类型 1:换电柜 2：租车 3：充电柜
								// 获取路由url的参数值
								deviceNo = _self.getUrlParam('deviceNo', res.result)
								deviceType = _self.getUrlParam('deviceType', res.result)
								if (deviceType == 2 || deviceType == 3) {
									_self.toast('请扫描正确的二维码！')
									return false
								}
								_self.$store.commit('scanCode', deviceType)
								if (deviceNo) {
									console.log('=======', deviceType, deviceNo, res);
									// const resss = await deviceReturnOpenDoor({
									// 	deviceNo: deviceNo,
									// 	handlerType: 3, //3寄存电池 4押金退还电池
									// })
									const resss = await holdUseHoldV2({
										deviceNo: deviceNo,
										day: _self.Bnum === 7 ? _self.inputValue : _self
											.Bnum + 1, //寄存天数
									})
									console.log('resss', resss);
									if (resss.code === 200) {
										let num = _self.Bnum + 1
										let numss = num === 8 ? _self.inputValue : num
										console.log('归还成功', _self.Bnum, _self.inputValue, numss);
										_self.routerLink({
											path: '/pages/user/wallet/openDoorss',
											query: {
												list: JSON.stringify(resss.data),
												handlerType: 3,
												numberDay: numss,
												deviceNo: deviceNo,
											}
										})


										// let num = _self.Bnum + 1
										// const en = await holdUseHold({
										// 	day: num === 8 ? _self.inputValue : num,
										// })
										// if (en.code === 200) {
										// 	_self.toast('寄存成功')
										// 	setTimeout(() => {
										// 		_self.ScanssFn(deviceNo)
										// 		_self.LoadFn()
										// 	}, 2000)
										// }
									} else {
										_self.toast(resss.msg || '寄存失败')
									}


								} else {
									_self.toast('扫码失败')
								}
							} else {
								_self.toast('请扫正确的二维码')
							}
						}
					},
					// 扫码失败
					fail(err) {
						_self.toast('扫码失败')
					}
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.BtopList {
		margin-top: 40upx;

		.BtopList1 {
			display: flex;
			flex-wrap: wrap;

			.BtopListOne {
				width: 30%;

				.BtopListOne1 {
					width: 90%;
					border: 1upx solid #aaa;
					border-radius: 20upx;
					padding: 25upx;
					margin-right: 4%;
					margin-bottom: 22upx;
					margin-top: 1.5%;
					display: inline-block;
					text-align: center;
				}
			}
		}

		.BtopListTwo {
			margin-top: 2%;
			text-align: center;
			font-size: 26upx;
			color: #888;
			font-size: 30upx;
			font-weight: 700;
		}
	}

	.Bconent {
		position: absolute;
		top: 42%;
		width: 90%;
		box-shadow: 3px 2px 6px 1px #bbb;
		padding: 20upx;
		// border-radius: 10upx;
	}

	.Bfooter {
		position: absolute;
		bottom: 14%;
		width: 90%;
		padding: 30upx;
		// box-shadow: 3px 2px 6px 1px #bbb;
		background-color: #eee;

		.BfooterTitle {
			text-align: center;
			font-size: 34upx;
			line-height: 34upx;
			font-weight: 700;
			margin-top: 20upx;
			margin-bottom: 20upx;
		}

		.Bfooterp {
			line-height: 46upx;
		}
	}

	.BfooterF {
		position: absolute;
		bottom: 5%;
		width: 90%;
	}

	.blue {
		background-color: #2879fc;
		color: #fff;
		border: 1upx solid #fff;

	}





	.one {
		margin-bottom: 90upx;
	}

	.oneTitle {
		font-size: 36upx;
		font-weight: 700;
		margin-bottom: 20upx;
		color: #777;
	}

	.twoTitle {
		color: red;
	}

	.threeTitle {
		color: green;
	}

	.tables {
		min-width: 90%;
		// display: flex;
		// justify-content: center;
	}

	u-tr {
		// display: flex;
		// justify-content: center;
		// align-items: center;
		// border: 0.5upx solid #aaa;
		font-size: 24upx !important;

	}

	.u-tr {
		text-align: center;
	}

	// .trth {
	// 	background-color: aqua !important;

	// }

	// .twoTrth {
	// 	background-color: blue;

	// }

	.u-th {
		// border: 0.5upx solid #aaa;
		padding-bottom: 10upx;
		padding-top: 10upx;
		text-align: center;
		min-height: 60upx;
		min-width: 13%;
	}

	.u-td {
		// border: 0.5upx solid #aaa;

		padding-bottom: 10upx;
		padding-top: 10upx;
		min-width: 13%;
		min-height: 70upx;
		text-align: center;
		// line-height: 70upx;
		word-break: break-all;
		/* 规定段落中的文本不进行换行： */
		white-space: nowrap;
		/* 内容会被修剪，并且其余内容是不可见的。 */
		overflow: hidden;
		/* 显示省略符号来代表被修剪的文本。 */
		text-overflow: ellipsis;

	}

	.aa {
		min-width: 210upx !important;
	}

	.qq {
		min-width: 130upx !important;
	}

	.zz {
		min-width: 210upx !important;
	}

	.ww {
		min-width: 120upx !important;
	}

	.green {
		font-weight: 700;

		color: red !important;
		// background-color: aqua;
	}

	.greens {
		color: green;
	}

	.reds {
		color: red;
	}

	.blues {
		color: blue;
	}

	.slot-content {
		font-size: 28rpx;
		color: $u-content-color;
		padding-left: 30rpx;
		margin-top: 16upx;
		line-height: 50upx;
		margin-bottom: 20upx;
	}
</style>